package com.example.lib_common.base

import android.os.Bundle
import android.view.MotionEvent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.example.lib_common.base.internal.InternalBaseActivity
import com.example.lib_common.utils.hideSoftKeyboard
import com.example.lib_common.utils.shouldHideInput

open class BaseMvvmActivity<VB : ViewDataBinding, VM : BaseViewModel>(private val factory: ViewModelProvider.Factory? = null) :
    InternalBaseActivity() {
    val mBinding: VB by lazy(mode = LazyThreadSafetyMode.NONE) {
        getViewBinding(layoutInflater)
    }
    val mViewModel: VM by lazy(mode = LazyThreadSafetyMode.NONE) {
        createViewModel(factory)
    }

    private var permissionCallback: ((Map<String, Boolean>) -> Unit)? = null
    private val permissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
            permissionCallback?.invoke(result)
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        beforeOnCreate(savedInstanceState)
        super.onCreate(savedInstanceState)
        afterOnCreate(savedInstanceState)
        enableEdgeToEdge()
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.root) { view, insets: WindowInsetsCompat ->
            //监听键盘
            val imeWindow = insets.getInsets(WindowInsetsCompat.Type.ime())
            softKeyboardCallBack(imeWindow.bottom)

            //为需要偏移的view设置padding
            val systemWindow = insets.getInsets(getInsetTypeMask())
            if (getInsetTypeMask() != 0) {
                mBinding.root.setPadding(0, systemWindow.top, 0, systemWindow.bottom)
            }
            insets
        }

        setContentView(mBinding.root)
        initView()
        initListener()
        initObserver()
    }

    open fun beforeOnCreate(savedInstanceState: Bundle?) {}
    open fun afterOnCreate(savedInstanceState: Bundle?) {}
    open fun getInsetTypeMask(): Int {
        return WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()
    }

    //点击是否隐藏键盘
    open fun isHideInput(): Boolean {
        return true
    }

    open fun initView() {

    }

    open fun initListener() {

    }

    open fun initObserver() {

    }

    //键盘弹出回调
    open fun softKeyboardCallBack(keyboardHeight: Int) {

    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (isHideInput()) {
            currentFocus.shouldHideInput(ev)?.hideSoftKeyboard()
        }
        return super.dispatchTouchEvent(ev)
    }

    /** 请求权限（单个或多个都用这个方法） */
    fun requestPers(permissions: List<String>, callback: (Map<String, Boolean>) -> Unit) {
        permissionCallback = callback
        permissionLauncher.launch(permissions.toTypedArray())
    }

    /** 单个权限快捷方法 */
    fun requestPer(permission: String, callback: (Boolean) -> Unit) {
        requestPers(listOf(permission)) { result ->
            callback(result[permission] ?: false)
        }
    }

    fun isPermissionDeniedForever(permission: String): Boolean {
        // 当 shouldShowRequestPermissionRationale 返回 false 且权限未授予时
        return checkSelfPermission(permission) != android.content.pm.PackageManager.PERMISSION_GRANTED && !shouldShowRequestPermissionRationale(
            permission
        )
    }

}